using GTA;
using GTA.Native;
using System;
using System.Drawing;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;

public class PlanesHails : Script
{
    bool Activated = false;
    bool AlwaysFollow = false;
    bool MenuShown = false;
    bool Planageddon = false;
    Keys ActivationKey = Keys.F6;
    int SpawnRadiusAroundPlayer = 150;
    int CrashRadiusAroundPlayer = 150;
    int PlanesHeigth = 150;
    int PlaneCount = 10;
    int SpawnedPlaneCount = 0;
    int PlanageddonTime = 0;
    int PlanageddonTimebetweenspawns = 15;
    Random rnd = new Random();
    string AddressList = "";
    bool KeyDownIsTrue = false;
    bool MinusX = false;
    bool MinusY = false;
    string SettingFileName = AppDomain.CurrentDomain.BaseDirectory + "\\PlanesHailsConfig.txt";
    string[] PlaneAddressInList;
    Color FooterColor = Color.FromArgb(200, 51, 153, 255);
    Color FooterTextColor = System.Drawing.Color.FromArgb(200, 255, 255, 255);
    Color HeaderColor = System.Drawing.Color.FromArgb(200, 51, 153, 255);
    Color HeaderTextColor = Color.FromArgb(200, 255, 255, 255);
    Color SelectedItemColor = System.Drawing.Color.FromArgb(200, 51, 153, 255);
    Color SelectedTextColor = System.Drawing.Color.FromArgb(200, 0, 0, 0);
    Color UnselectedItemColor = System.Drawing.Color.FromArgb(200, 102, 255, 255);
    Color UnselectedTextColor = System.Drawing.Color.FromArgb(200, 0, 0, 0);
    List<GTA.Vehicle> Planes = new List<GTA.Vehicle>();
    int MenuWidth = 300;

    public PlanesHails()
      {
          LoadSettings();
          AddressList = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\Planes.txt");
          PlaneAddressInList = AddressList.Split(',');
          KeyUp += OnKeyUp;
          Tick += OnTick;
          KeyDown += OnKeyDown;
      }

       void OnKeyUp(object sender, KeyEventArgs e)
       {
           if (KeyDownIsTrue)
           {
               if (e.KeyCode == ActivationKey)
               {
                   if (MenuShown == false)
                   {
                       MenuShown = true;
                       ShowMenu();
                   }
                   else if (MenuShown == true)
                   {
                       View.CloseAllMenus();
                       MenuShown = false;
                   }
                   KeyDownIsTrue = false;
               }
           }
       }

       void OnKeyDown(object sender, KeyEventArgs e)
       {
           if (e.KeyCode == ActivationKey)
           {
               if (KeyDownIsTrue == false)
               {
                   if (e.KeyCode == ActivationKey)
                   {
                       KeyDownIsTrue = true;
                   }
               }
           }
       }

    void LoadSettings()
    {
        string[] Line = File.ReadAllText(SettingFileName).Split('\n');
        ActivationKey = (Keys)Enum.Parse(typeof(Keys), Line[0].Split('=')[1]);
        SpawnRadiusAroundPlayer = int.Parse(Line[1].Split('=')[1]);
        PlanesHeigth = int.Parse(Line[2].Split('=')[1]);
        PlaneCount = int.Parse(Line[3].Split('=')[1]);
        PlanageddonTimebetweenspawns = int.Parse(Line[4].Split('=')[1]);
        CrashRadiusAroundPlayer = int.Parse(Line[5].Split('=')[1]);
        FooterColor = Color.FromArgb(int.Parse(Line[6].Split('=')[1].Split(',')[0]), int.Parse(Line[6].Split('=')[1].Split(',')[1]), int.Parse(Line[6].Split('=')[1].Split(',')[2]), int.Parse(Line[6].Split('=')[1].Split(',')[3]));
        FooterTextColor = System.Drawing.Color.FromArgb(int.Parse(Line[7].Split('=')[1].Split(',')[0]), int.Parse(Line[7].Split('=')[1].Split(',')[1]), int.Parse(Line[7].Split('=')[1].Split(',')[2]), int.Parse(Line[7].Split('=')[1].Split(',')[3]));
        HeaderColor = System.Drawing.Color.FromArgb(int.Parse(Line[8].Split('=')[1].Split(',')[0]), int.Parse(Line[8].Split('=')[1].Split(',')[1]), int.Parse(Line[8].Split('=')[1].Split(',')[2]), int.Parse(Line[8].Split('=')[1].Split(',')[3]));
        HeaderTextColor = Color.FromArgb(int.Parse(Line[9].Split('=')[1].Split(',')[0]), int.Parse(Line[9].Split('=')[1].Split(',')[1]), int.Parse(Line[9].Split('=')[1].Split(',')[2]), int.Parse(Line[9].Split('=')[1].Split(',')[3]));
        SelectedItemColor = System.Drawing.Color.FromArgb(int.Parse(Line[10].Split('=')[1].Split(',')[0]), int.Parse(Line[10].Split('=')[1].Split(',')[1]), int.Parse(Line[10].Split('=')[1].Split(',')[2]), int.Parse(Line[10].Split('=')[1].Split(',')[3]));
        SelectedTextColor = System.Drawing.Color.FromArgb(int.Parse(Line[11].Split('=')[1].Split(',')[0]), int.Parse(Line[11].Split('=')[1].Split(',')[1]), int.Parse(Line[11].Split('=')[1].Split(',')[2]), int.Parse(Line[11].Split('=')[1].Split(',')[3]));
        UnselectedItemColor = System.Drawing.Color.FromArgb(int.Parse(Line[12].Split('=')[1].Split(',')[0]), int.Parse(Line[12].Split('=')[1].Split(',')[1]), int.Parse(Line[12].Split('=')[1].Split(',')[2]), int.Parse(Line[12].Split('=')[1].Split(',')[3]));
        UnselectedTextColor = System.Drawing.Color.FromArgb(int.Parse(Line[13].Split('=')[1].Split(',')[0]), int.Parse(Line[13].Split('=')[1].Split(',')[1]), int.Parse(Line[13].Split('=')[1].Split(',')[2]), int.Parse(Line[13].Split('=')[1].Split(',')[3]));
        MenuWidth = int.Parse(Line[14].Split('=')[1]);
    }

    void SaveSettings()
    {
        File.WriteAllText(SettingFileName, ActivationKey.ToString() + Environment.NewLine + SpawnRadiusAroundPlayer.ToString() + Environment.NewLine + PlanesHeigth.ToString() + Environment.NewLine + PlaneCount.ToString() + Environment.NewLine + PlanageddonTimebetweenspawns.ToString() + Environment.NewLine + CrashRadiusAroundPlayer.ToString());
        GTA.UI.ShowSubtitle("Planes Hails Settings saved successfully", 1000);
    }

    void ShowMenu()
    {
        View.CloseAllMenus();
        GTA.MenuButton StartPlanageddonButton = new MenuButton("Start Planageddon", "Start the Planageddon");
        if (Planageddon == true)
        {
            StartPlanageddonButton = new MenuButton("Stop Planageddon", "Stop the Planageddon");
        }
        GTA.MenuButton StartButton = new MenuButton("Start", "Start the Planes Hail");
        GTA.MenuButton StopButton = new MenuButton("Stop", "Stop the Planes Hail");
        GTA.MenuToggle FollowButton = new MenuToggle("Follow", "Planes will always follow you");
        GTA.MenuButton IncreaseButton = new MenuButton("Increase Plane Count", "Increase Plane Count by 5");
        GTA.MenuButton DecreaseButton = new MenuButton("Decrease Plane Count", "Decrease Plane Count by 5");
        GTA.MenuButton IncreaseRadiusButton = new MenuButton("Increase Radius", "Increase Radius by 5");
        GTA.MenuButton DecreaseRadiusButton = new MenuButton("Decrease Radius", "Decrease Radius by 5");
        GTA.MenuButton IncreaseCrashRadiusButton = new MenuButton("Increase Crash Radius", "Increase Crash Radius by 5");
        GTA.MenuButton DecreaseCrashRadiusButton = new MenuButton("Decrease Crash Radius", "Decrease Crash Radius by 5");
        GTA.MenuButton SaveButton = new MenuButton("Save Current Settings", "Save Current Settings");
        GTA.MenuButton LoadButton = new MenuButton("Load Settings", "Load Settings");
        GTA.Menu ShownMenu = new GTA.Menu("Planes Hails", new GTA.IMenuItem[] {
        StartPlanageddonButton,
        StartButton,
        StopButton,
        FollowButton,
        IncreaseButton,
        DecreaseButton,
        IncreaseRadiusButton,
        DecreaseRadiusButton,
        IncreaseCrashRadiusButton,
        DecreaseCrashRadiusButton,
        SaveButton,
        LoadButton,
        });
        StartPlanageddonButton.Activated += (sender, args) => TogglePlanageddon();
        StartButton.Activated += (sender, args) => StartPlanesHails();
        StopButton.Activated += (sender, args) => StopPlanesHails();
        if (AlwaysFollow)
        {
            FollowButton.Value = true;
        }
        FollowButton.Changed += (sender, args) => ToggleAlwaysFollow();
        IncreaseButton.Activated += (sender, args) => Increase();
        DecreaseButton.Activated += (sender, args) => Decrease();
        IncreaseRadiusButton.Activated += (sender, args) => IncreaseRadius();
        DecreaseRadiusButton.Activated += (sender, args) => DecreaseRadius();
        IncreaseCrashRadiusButton.Activated += (sender, args) => IncreaseCrashRadius();
        DecreaseCrashRadiusButton.Activated += (sender, args) => DecreaseCrashRadius();
        SaveButton.Activated += (sender, args) => SaveSettings();
        LoadButton.Activated += (sender, args) => LoadSettings();
        ShownMenu.HeaderTextColor = HeaderTextColor;
        ShownMenu.HeaderColor = HeaderColor;
        ShownMenu.SelectedItemColor = SelectedItemColor;
        ShownMenu.SelectedTextColor = SelectedTextColor;
        ShownMenu.UnselectedItemColor = UnselectedItemColor;
        ShownMenu.UnselectedTextColor = UnselectedTextColor;
        ShownMenu.FooterColor = FooterColor;
        ShownMenu.FooterTextColor = FooterTextColor;
        ShownMenu.Width = MenuWidth;
        View.AddMenu(ShownMenu);
    }

    void TogglePlanageddon()
    {
        Planageddon = !Planageddon;
        ShowMenu();
    }

    void ToggleAlwaysFollow()
    {
        AlwaysFollow = !AlwaysFollow;
        ShowMenu();
    }

    private void OnTick(object sender, EventArgs e)
    {
        foreach (GTA.Vehicle Plane in Planes)
        {
            if (Plane != null)
            {
                if ((Plane.BodyHealth > 0.0f) || (Plane.EngineHealth > 0.0f) || (Plane.PetrolTankHealth > 0.0f))
                {
                    Plane.ApplyForce(Game.Player.Character.Position - Plane.Position, new GTA.Math.Vector3((float)(Math.Atan2(Plane.Position.X, Game.Player.Character.Position.X) * 180.0 / Math.PI), (float)(Math.Atan2(Plane.Position.Y, Game.Player.Character.Position.Y) * 180.0 / Math.PI), (float)(Math.Atan2(Plane.Position.Z, Game.Player.Character.Position.Z) * 180.0 / Math.PI)));
                }
            }
        }
        if (Planageddon == true)
        {
            if (PlanageddonTime < PlanageddonTimebetweenspawns)
            {
                PlanageddonTime += 1;
            }
            else
            {
                GetRandomBoolean("MinusX");
                GetRandomBoolean("MinusY");
                GTA.Math.Vector3 PlayerCoord = Game.Player.Character.Position;
                GTA.Math.Vector3 PlaneObjCoord = new GTA.Math.Vector3(0, 0, 0);
                if (MinusX == false)
                {
                    if (MinusY == false)
                    {
                        PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                    }
                    else
                    {
                        PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                    }
                }
                else
                {
                    if (MinusY == false)
                    {
                        PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                    }
                    else
                    {
                        PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                    }
                }
                GTA.Math.Vector3 RandomCoord = new GTA.Math.Vector3(rnd.Next(0, CrashRadiusAroundPlayer), rnd.Next(0, CrashRadiusAroundPlayer), PlayerCoord.Z);
                Spawn(PlaneAddressInList[rnd.Next(0, PlaneAddressInList.Length - 1)], PlayerCoord, PlaneObjCoord, RandomCoord);
                PlanageddonTime = 0;
            }
        }
        else
        {
            if (Activated == true)
            {
                if (SpawnedPlaneCount < PlaneCount)
                {
                    GetRandomBoolean("MinusX");
                    GetRandomBoolean("MinusY");
                    GTA.Math.Vector3 PlayerCoord = Game.Player.Character.Position;
                    GTA.Math.Vector3 PlaneObjCoord = new GTA.Math.Vector3(0, 0, 0);
                    if (MinusX == false)
                    {
                        if (MinusY == false)
                        {
                            PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                        }
                        else
                        {
                            PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                        }
                    }
                    else
                    {
                        if (MinusY == false)
                        {
                            PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y + rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                        }
                        else
                        {
                            PlaneObjCoord = new GTA.Math.Vector3(PlayerCoord.X - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Y - rnd.Next(0, SpawnRadiusAroundPlayer), PlayerCoord.Z + PlanesHeigth);
                        }
                    }
                    GTA.Math.Vector3 RandomCoord = new GTA.Math.Vector3(rnd.Next(0, CrashRadiusAroundPlayer), rnd.Next(0, CrashRadiusAroundPlayer), PlayerCoord.Z);
                    Spawn(PlaneAddressInList[rnd.Next(0, PlaneAddressInList.Length - 1)], PlayerCoord, PlaneObjCoord, RandomCoord);
                    SpawnedPlaneCount += 1;
                }
            }
        }
    }

    void GetRandomBoolean(string BooleanAddress)
    {
        if (BooleanAddress == "MinusX")
        {
            int ChangeStatusTo = rnd.Next(0, 2);
            if (ChangeStatusTo == 0)
            {
                MinusX = false;
            }
            else
            {
                MinusX = true;
            }
        }
        else
        {
            int ChangeStatusTo = rnd.Next(0, 2);
            if (ChangeStatusTo == 0)
            {
                MinusY = false;
            }
            else
            {
                MinusY = true;
            }
        }
    }

    void Spawn(string VehicleName, GTA.Math.Vector3 PlayerCoord, GTA.Math.Vector3 PlaneObjCoord, GTA.Math.Vector3 RandomCoord)
    {
        try
        {
            GTA.Vehicle PlaneObj = GTA.World.CreateVehicle(new GTA.Model(VehicleName), PlaneObjCoord);
            if (AlwaysFollow)
            {
                Planes.Add(PlaneObj);
            }
            try
            {
                PlaneObj.ApplyForce(PlayerCoord - PlaneObjCoord + RandomCoord, new GTA.Math.Vector3((float)(Math.Atan2(PlaneObjCoord.X, PlayerCoord.X + RandomCoord.X) * 180.0 / Math.PI), (float)(Math.Atan2(PlaneObjCoord.Y, PlayerCoord.Y + RandomCoord.Y) * 180.0 / Math.PI), (float)(Math.Atan2(PlaneObjCoord.Z, PlayerCoord.Z + RandomCoord.Z) * 180.0 / Math.PI)));
            }
            catch (Exception exception)
            {
                File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\Planes Hails Error.log", exception.StackTrace + exception.Message + "(Current Vehicle Name = " + VehicleName + ")");
                return;
            }
            PlaneObj.MarkAsNoLongerNeeded();
        }
        catch (Exception exception)
        {
            File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "\\Planes Hails Error.log", exception.StackTrace + exception.Message + "(Current Vehicle Name = " + VehicleName + ")");
            return;
        }
    }

    void StartPlanesHails()
    {
        if (Activated == false)
        {
            SpawnedPlaneCount = 0;
            Activated = !Activated;
            UI.Notify("Planes Hails Mod has been activated!");
        }
    }

    void StopPlanesHails()
    {
        if (Activated == true)
        {
            SpawnedPlaneCount = 0;
            Activated = !Activated;
            UI.Notify("Planes Hails Mod has been deactivated!");
        }
    }

    void Increase()
    {
        PlaneCount += 5;
        GTA.UI.ShowSubtitle("Current Plane Count: " + PlaneCount.ToString(), 1000);
    }

    void Decrease()
    {
        if (PlaneCount > 5)
        {
            PlaneCount -= 5;
            GTA.UI.ShowSubtitle("Current Plane Count: " + PlaneCount.ToString(), 1000);
        }
    }

    void IncreaseRadius()
    {
        SpawnRadiusAroundPlayer += 5;
        GTA.UI.ShowSubtitle("Current Radius: " + SpawnRadiusAroundPlayer.ToString(), 1000);
    }

    void DecreaseRadius()
    {
        if (SpawnRadiusAroundPlayer > 5)
        {
            SpawnRadiusAroundPlayer -= 5;
            GTA.UI.ShowSubtitle("Current Radius: " + SpawnRadiusAroundPlayer.ToString(), 1000);
        }
    }

    void IncreaseCrashRadius()
    {
        CrashRadiusAroundPlayer += 5;
        GTA.UI.ShowSubtitle("Current Crash Radius: " + CrashRadiusAroundPlayer.ToString(), 1000);
    }

    void DecreaseCrashRadius()
    {
        if (SpawnRadiusAroundPlayer > 5)
        {
            CrashRadiusAroundPlayer -= 5;
            GTA.UI.ShowSubtitle("Current Crash Radius: " + CrashRadiusAroundPlayer.ToString(), 1000);
        }
    }
}